package top.eggcode.common.mvc;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.eggcode.common.error.ApplicationException;
import top.eggcode.common.lang.BeanUnit;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;

/**
 * 参数校验器
 * Created at 2022/1/20 10:42
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public final class ParamValidator {

    private final static Logger logger = LoggerFactory.getLogger(ParamValidator.class);

    /**
     * 检查必填项
     * 值为 null 、空字符串、空格，都视为失败
     *
     * @param subject
     * @param fields
     */
    public static void required(Object subject, String... fields) {

        for (String fieldName : fields) {
            try {
                Object val = BeanUnit.getAttributeValue(fieldName, subject);
                if (val == null) {
                    throw new ApplicationException("字段 [" + fieldName + "] 不能为空");
                }

                if (val.getClass() == String.class) {
                    if (StringUtils.isBlank((String) val)) {
                        throw new ApplicationException("字段 [" + fieldName + "] 不能为空格或者空字符串");
                    }
                }
            } catch (InvocationTargetException | IllegalAccessException | IntrospectionException e) {
                e.printStackTrace();
                throw new ApplicationException("无法获取字段值，字段可能不存在");
            }

        }

        logger.debug("[参数校验器]: " + subject.getClass().getName() + "，检查通过");

    }
}
